﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using Reborn_Server.App1AppHandler;
using App1AppHandler;

namespace Reborn_WorldServer.App1AppHandler
{
    public class MailItem
    {
        private int _ID;
        public int ID
        {
            get { return _ID; }
        }

        private int _FromCharacterID;
        private string _FromCharacterName;
        private string _Subject;
        private string _Message = "";
        private int _Coins;
        private int _Expires;

        private List<Loot> _Attachments = new List<Loot>();

        public MailItem(int ID, int FromCharacterID, string FromCharacterName, string Subject, string Message, int Coins, int Expires)
        {
            _ID = ID;
            _FromCharacterID = FromCharacterID;
            _FromCharacterName = FromCharacterName;
            _Subject = Subject;
            _Message = Message;
            _Coins = Coins;
            _Expires = Expires;
        }

        public void addAttachment(Loot attachment)
        {
            _Attachments.Add(attachment);
        }

        public string toXML(Character sendingToCharacter)
        {
            string result = "";

            StringWriter stringWriter = new StringWriter();
            XmlTextWriter xmldoc = new XmlTextWriter(stringWriter);

            xmldoc.WriteStartElement("mailitem");
            xmldoc.WriteAttributeString("id", _ID.ToString());
            xmldoc.WriteAttributeString("fromcharacterid", _FromCharacterID.ToString());
            xmldoc.WriteAttributeString("fromcharactername", _FromCharacterName.ToString());
            xmldoc.WriteAttributeString("expires", _Expires.ToString());
            xmldoc.WriteAttributeString("coins", _Coins.ToString());

            xmldoc.WriteStartElement("subject");
            xmldoc.WriteRaw(Message.escapeXmlText(_Subject));
            xmldoc.WriteEndElement();

            xmldoc.WriteStartElement("message");
            xmldoc.WriteRaw(Message.escapeXmlText(_Message));
            xmldoc.WriteEndElement();

            xmldoc.WriteStartElement("attachments");
            
            foreach (Loot loot in _Attachments)
                xmldoc.WriteRaw(loot.toXML(sendingToCharacter));

            xmldoc.WriteEndElement();

            xmldoc.WriteEndElement();
            xmldoc.Flush();

            xmldoc.Close();

            stringWriter.Flush();

            result = stringWriter.ToString();

            return result;
        }
    }
}
